<!DOCTYPE html>
<html>
<head>
  <title>osm buildings demo</title>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maptalks/dist/maptalks.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/maptalks/dist/maptalks.min.js"></script>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/three@0.97.0/build/three.min.js"></script>
  <script type="text/javascript" src="../dist/maptalks.heatmap.js"></script>
  <script type="text/javascript" src="../dist/maptalks.three.js"></script>
  <script type="text/javascript" src="buildings.js"></script>
  <script type="text/javascript" src="realworld.10000.js"></script>
  <style>
    html,body{
        margin:0px;realworld.10000
        height:100%;
        width: 100%;
    }
    #map { width: 1000px; height: 700px; background-color : #000;}
  </style>
</head>
<body>
<div id="map"></div>
<script>

var map = new maptalks.Map("map",{
    center : [ 1.96896900042, 33.60216000018],
    zoom   :  3,
    pitch : 40,
    centerCross : false,
    doubleClickZoom : false,
    baseLayer : new maptalks.TileLayer('tile',{
        urlTemplate:"http://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=16cf3e74eac8e6a6a0dde240275f8442",
        subdomains: ["1", "2", "3", "4", "7", "6", "5"],
        attribution: '天地图'
    })
});


let colorlist = {
        徐州市: "#fff260",
        连云港市: "#20c4f3",
        盐城市: "#20c4f3",
        淮安市: "#20c4f3",
        宿迁市: "#f28a24",
        扬州市: "#f43d42",
        南京市: "#f28a24",
        镇江市: "#CFDC72",
        泰州市: "#f28a24",
        南通市: "#fff260",
        常州市: "#20c4f3",
        无锡市: "#fff260",
        苏州市: "#20c4f3"
    }

hotValue = [];
function getGeometryByRegion(region) {
    let coordinates = region.split(",").map(p => {
        return p.split(" ").map(str => parseFloat(str))
    });

    return {
        type: "Polygon",
        coordinates,
    }
}
function getBordersFeature() {
      let postStr = {
        searchWord: "江苏",
        searchType: "1",
        needSubInfo: "true",
        needAll: "true",
        needPolygon: "true",
        needPre: "true"
      };
    return $.getJSON(`http://api.tianditu.gov.cn/administrative?postStr=${JSON.stringify(postStr)}&tk=16cf3e74eac8e6a6a0dde240275f8442`)
    .then(data => {
        console.log(data.data[0], "data")
        let wholeGeometryJSON = getGeometryByRegion(data.data[0].points[0].region)
        let wholeGeometry = maptalks.GeoJSON.toGeometry(wholeGeometryJSON)
        let wholeCenter = wholeGeometry.getCenter();
        map.setCenter([wholeCenter.x, wholeCenter.y])
        map.fitExtent(wholeGeometry.getExtent(), 0.75);
        features = data.data[0].child.map((cityjson, i) => {
            let geometry = getGeometryByRegion(cityjson.points[0].region)
            for(let x = 0 ; x < Math.random() * 500; x++) {
                hotValue.push([(Math.random()/40000+1)*cityjson.lnt, (Math.random()/40000+1)*cityjson.lat, (Math.random()) ])
            }
            return {
                "properties":{
                    level:10 + 100 * i,
                    color: colorlist[cityjson.name],
                    ...cityjson
                },
                geometry,
                "type":"Feature"
            }
        })
        return [{
            "type":"FeatureCollection",
            features
        }]
    });
}
getBordersFeature().then(buildings2 => {
    buildings = buildings2
    // features to draw
    var features = [];
    buildings.forEach(function (b) {
        features = features.concat(b.features);
    });

    // the ThreeLayer to draw buildings
    var threeLayer = new maptalks.ThreeLayer('t', {
        forceRenderOnMoving : true,
        forceRenderOnRotating : true
    });
    threeLayer.prepareToDraw = function (gl, scene, camera) {
        var me = this;
        var light = new THREE.DirectionalLight(0x00ffff);
        light.position.set(1, 1, 1).normalize();
        scene.add(light);

        features.forEach(function (g) {
            var heightPerLevel = 10000;
            var levels = g.properties.levels || 1;
            var color =  g.properties.color // getColor(levels);

            var m = new THREE.MeshPhongMaterial({color: color, opacity : 0.7});
            //change to back side with THREE <= v0.94
            // m.side = THREE.BackSide;
            var gObj = maptalks.GeoJSON.toGeometry(g);
            gObj.setProperties(g)
            console.log(gObj.getProperties(), "get")
            var mesh = me.toExtrudeMesh(gObj, levels * heightPerLevel, m, levels * heightPerLevel);
            if (Array.isArray(mesh)) {
            scene.add.apply(scene, mesh);
            } else {
            scene.add(mesh);
            }
        });
    };
    threeLayer.addTo(map);
    txtlayer = new maptalks.TileLayer("boudaries", {
            urlTemplate:
              "http://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=16cf3e74eac8e6a6a0dde240275f8442",
            subdomains: ["1", "2", "3", "4", "7", "6", "5"]
          });

    txtlayer.addTo(map)

    var data = hotValue.map(function (p) { return [p[0], p[1],p[2]]; });
    var heatlayer = new maptalks.HeatLayer('heat', data, {
        // 'heatValueScale': 0.2,
        // 'forceRenderOnRotating' : true,
        // 'forceRenderOnMoving' : true,
        heatValueScale: 0.7,
        'radius' : 50,
        // 'blur' : 10,
        max:10,
        'gradient' : { 0.3: 'blue', 0.6:'yellow',0.9: 'red' }
    }).addTo(map);

    //select buildings by mouse click
    var raycaster = new THREE.Raycaster();

    document.addEventListener('dblclick', function (event) {
        event.preventDefault();
        var mouse = new THREE.Vector2();
        // 屏幕点击坐标转 ndc 设备无关坐标，[-1, 1]
        var renderer = threeLayer.getThreeRenderer();
        var rendererSize = renderer.getSize();
        mouse.x = (event.clientX / rendererSize.width) * 2 - 1;
        mouse.y = -(event.clientY / rendererSize.height) * 2 + 1;

        var objects = [];
        threeLayer.getScene().children.forEach(child => {
            if (child instanceof THREE.Mesh) {
            objects.push(child);
            }
        })
        raycaster.setFromCamera(mouse, threeLayer.getCamera());
        var intersects = raycaster.intersectObjects(objects);
        if (intersects.length > 0) {
            console.log('Mesh : ', intersects);
            map.fitExtent(intersects[0].object.extPolygon.getExtent(), 0.25);
        }
    }, false);

    function getColor(level) {
        if (level < 2) {
            return 0x2685a7;
        } else if (level >= 2 && level <= 5) {
            return 0xff5733;
        } else {
            return 0xff2e00;
        }
    }
})
</script>
</body>
</html>
